<script setup lang="ts" name="applyForm">
import { ApplyForm, ApplyVO } from '@/api/fill/apply/types';
import { AxiosResponse } from 'axios';
import { startWorkFlow } from '@/api/workflow/task';
import { StartProcessBo } from '@/api/workflow/workflowCommon/types';
import SubmitVerify from '@/components/Process/submitVerify.vue';
import ApprovalRecord from '@/components/Process/approvalRecord.vue';
import { addApply, getApply, updateApply } from '@/api/fill/apply';
import { getAllSubjectList } from '@/api/collect/allocation';
import { BudgetSubjectVO } from '@/api/budget/budgetSubject/types';
import { TableEnum } from '@/enums/business/TableEnum';
import { options } from '@/hooks/useCommon';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const initFormData: ApplyForm = {
  id: undefined,
  year: undefined,
  yardCode: undefined,
  yardName: undefined,
  deptCode: undefined,
  deptName: undefined,
  applyTheme: undefined,
  subjectCode: undefined,
  subjectName: undefined,
  applyMoney: undefined,
  ossId: undefined,
  status: undefined,
  quarter: undefined,
  remark: undefined
};

const form = ref<ApplyForm>(initFormData);

const applyFormRef = ref<ElFormInstance>();

const rules = {
  applyTheme: [{ required: true, message: '申请主题不能为空', trigger: 'blur' }],
  subjectCode: [{ required: true, message: '预算科目编码不能为空', trigger: 'blur' }],
  quarter: [{ required: true, message: '季度不能为空', trigger: 'blur' }],
  applyMoney: [
    { required: true, message: '申请金额不能为空', trigger: 'blur' },
    {
      validator: (rule: any, value: any, callback: any): void => {
        if (value > 100000000) {
          form.value.applyMoney = 100000000;
          callback(new Error('申请金额不能大于100000000'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
};

const subjectList = ref<BudgetSubjectVO[]>([]);

/**预算科目列表下拉*/
const getSubjectList = async () => {
  getAllSubjectList().then((res) => {
    subjectList.value = res.data;
  });
};

/**选中的预算科目*/
const selectSubject = (value: any) => {
  form.value.subjectName = subjectList.value.find((item) => item.subjectCode === value).subjectName;
};

const buttonLoading = ref(false);

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  applyFormRef.value?.resetFields();
};

const loading = ref(false);
//路由参数
const routeParams = ref<Record<string, any>>({});

/** 获取详情 */
const getInfo = () => {
  loading.value = true;
  buttonLoading.value = false;
  nextTick(async () => {
    const res = await getApply(routeParams.value.id);
    Object.assign(form.value, res.data);

    form.value.year = res.data.year;
    loading.value = false;
    buttonLoading.value = false;
  });
};

/** 提交按钮 */
const submitForm = (status: string) => {
  try {
    applyFormRef.value?.validate(async (valid: boolean) => {
      form.value.status = status;

      if (valid) {
        buttonLoading.value = true;
        let res: AxiosResponse<ApplyVO>;
        if (form.value.id) {
          res = await updateApply(form.value);
        } else {
          res = await addApply(form.value);
        }

        form.value = res.data;

        /*提交工作流程*/
        await handleStartWorkFlow(res.data);
      }
    });
  } finally {
    buttonLoading.value = false;
  }
};

//提交组件
const submitVerifyRef = ref<InstanceType<typeof SubmitVerify>>();
//审批记录组件
const approvalRecordRef = ref<InstanceType<typeof ApprovalRecord>>();
const submitFormData = ref<StartProcessBo>({
  businessKey: '',
  tableName: '',
  variables: {}
});
const taskVariables = ref<Record<string, any>>({});
//提交申请
const handleStartWorkFlow = async (data: ApplyVO) => {
  try {
    submitFormData.value.tableName = TableEnum.FILL_ACT_BUDGET_APPLY;
    submitFormData.value.businessKey = data.id;
    //流程变量
    taskVariables.value = {
      entity: data,
      purchaseDeptName: data.deptName, //采购申请部门名称
      deptName: '/',
      applyMoney: data.applyMoney,
      userList: [1, 3],
      userList2: [1, 3]
    };
    submitFormData.value.variables = taskVariables.value;
    const resp = await startWorkFlow(submitFormData.value);

    if (submitVerifyRef.value) {
      buttonLoading.value = false;
      submitVerifyRef.value.openDialog(resp.data.taskId);
    }
  } finally {
    buttonLoading.value = false;
  }
};
//审批记录
const handleApprovalRecord = () => {
  approvalRecordRef.value.init(form.value.id);
};
//提交回调
const submitCallback = async () => {
  await proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};

//返回
const goBack = () => {
  proxy.$tab.closePage(proxy.$route);
  proxy.$router.go(-1);
};
//审批
const approvalVerifyOpen = async () => {
  submitVerifyRef.value.openDialog(routeParams.value.taskId);
};

//校验提交按钮是否显示
const submitButtonShow = computed(() => {
  return (
    routeParams.value.type === 'add' ||
    (routeParams.value.type === 'update' &&
      form.value.status &&
      (form.value.status === 'draft' || form.value.status === 'cancel' || form.value.status === 'back'))
  );
});

//校验审批按钮是否显示
const approvalButtonShow = computed(() => {
  return routeParams.value.type === 'approval' && form.value.status && form.value.status === 'waiting';
});
//组件禁用
const disabled = ref(false);
onMounted(() => {
  getSubjectList();
  nextTick(async () => {
    routeParams.value = proxy.$route.query;
    reset();
    loading.value = false;
    if (routeParams.value.type === 'update' || routeParams.value.type === 'view' || routeParams.value.type === 'approval') {
      getInfo();
      //禁用编辑
      disabled.value = routeParams.value.type === 'view' || routeParams.value.type === 'approval';
    } else if (routeParams.value.type === 'add') {
      form.value = {
        yardCode: routeParams.value.yardCode,
        yardName: routeParams.value.yardName,
        year: routeParams.value.year,
        deptName: routeParams.value.deptName,
        deptCode: routeParams.value.deptCode
      };
    }
  });
});
</script>

<template>
  <div class="app-container">
    <!-- 顶部操作栏 -->
    <div class="top-nav custom-flex-between">
      <!-- 查询条件 -->
      <el-form ref="applyFormRef" :model="form" :inline="true" label-width="80px" class="header-form">
        <el-form-item label="年份" prop="year" class="form-item-compact">
          <el-date-picker v-model="form.year" type="year" format="YYYY" value-format="YYYY" disabled style="width: 190px" />
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName" class="form-item-compact">
          <el-input v-model="form.deptName" disabled placeholder="-" class="w-200" />
        </el-form-item>
        <el-form-item label="院区名称" prop="yardName" class="form-item-compact">
          <el-input v-model="form.yardName" disabled class="w-200" />
        </el-form-item>
      </el-form>

      <!-- 操作按钮组 -->
      <div class="action-btns">
        <el-button v-if="submitButtonShow" type="primary" :loading="buttonLoading" @click="submitForm('waiting')" icon="CircleCheck">
          提交
        </el-button>
        <el-button v-if="approvalButtonShow" type="primary" :loading="buttonLoading" @click="approvalVerifyOpen" icon="Promotion"> 审批 </el-button>
        <el-button v-if="form?.id && form.status !== 'draft'" type="primary" @click="handleApprovalRecord" icon="View"> 流程进度 </el-button>
        <el-button type="danger" @click="goBack()">
          <svg-icon icon-class="back" class="mr-5" />
          返回
        </el-button>
      </div>
    </div>

    <!-- 表单主体 -->
    <el-card shadow="never" class="form-card">
      <el-form ref="applyFormRef" :model="form" :rules="!disabled ? rules : null" label-width="100px">
        <el-row :gutter="30">
          <!-- 左列 -->
          <el-col :span="12">
            <el-form-item label="申请季度" prop="quarter">
              <el-select v-model="form.quarter" :disabled="disabled" class="w-full">
                <el-option v-for="item in options" :key="item.quarter" :label="item.label" :value="item.quarter" />
              </el-select>
            </el-form-item>
            <el-form-item label="预算科目" prop="subjectCode">
              <el-select v-model="form.subjectCode" :disabled="disabled" class="w-full" filterable @change="selectSubject">
                <el-option
                  v-for="item in subjectList"
                  :key="item.subjectCode"
                  :label="`${item.subjectCode} - ${item.subjectName}`"
                  :value="item.subjectCode"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <!-- 右列 -->
          <el-col :span="12">
            <el-form-item label="申请主题" prop="applyTheme">
              <el-input v-model="form.applyTheme" :disabled="disabled" placeholder="请输入申请主题" class="w-full" maxlength="50" />
            </el-form-item>
            <el-form-item label="申请金额" prop="applyMoney">
              <el-input v-model="form.applyMoney" type="number" :disabled="disabled" placeholder="请输入金额" class="w-full">
                <template #append>万元</template>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 跨列项 -->
        <el-form-item label="申请备注" prop="remark">
          <el-input
            v-model="form.remark"
            :disabled="disabled"
            type="textarea"
            :autosize="{ minRows: 4 }"
            placeholder="请输入备注信息"
            class="w-full"
            maxlength="800"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 其他组件 -->
    <submitVerify ref="submitVerifyRef" :task-variables="taskVariables" @submit-callback="submitCallback" />
    <approvalRecord ref="approvalRecordRef" />
  </div>
</template>

<style scoped lang="scss">
.app-container {
  padding: 10px;
}

/* 顶部操作栏布局 */
.top-nav {
  margin-bottom: 10px;
  padding: 20px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 1px 0 #fff;
}

.header-form {
  flex: 1;
  margin-right: 20px;
}

.action-btns {
  flex-shrink: 0;
}

/* 表单卡片样式 */
.form-card {
  padding-top: 20px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
  background-color: #fff;
  height: 80vh;
}

/* 紧凑表单项 */
.form-item-compact {
  margin-bottom: 0;
}

/* 统一输入控件宽度 */
.w-160 {
  width: 150px;
}

.w-200 {
  width: 200px;
}

.w-full {
  width: 100%;
}

/* 按钮图标间距 */
.mr-5 {
  margin-right: 5px;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .top-nav {
    flex-direction: column;
  }

  .header-form {
    margin-right: 0;
    margin-bottom: 10px;
  }

  .action-btns {
    width: 100%;
    justify-content: flex-end;
  }
}
</style>
